import { certificateDelete, findEcuPlanByIdAndType , ecuInPlan, findEcuCertStatus} from '@/services/equipmentCertificate';
import { message } from 'antd'

export default {
  namespace: 'equipmentCertificate',

  state: {
    data: {
      list: [],
      pagination: {},
    },
    loading: true,
  },
  effects: {
    *fetch({ payload, callback }, { call, put }) {
      yield put({
        type: 'loading',
        payload: true,
      });
      if (!payload || !payload.ecuId) {
        message.warning('请填写设备编号');
        return;
      }
      if (!payload || !payload.ecuType) {
        message.warning('请选择设备类型');
        return;
      }
      const ecuInPlanResponse = yield call(ecuInPlan, payload);

      if(ecuInPlanResponse.data) {
        const response = yield call(findEcuPlanByIdAndType, payload);
        const responseStatus = yield call(findEcuCertStatus, payload);
        
        if (response.statusCode == "0" && response.data) {
          yield put({
            type: 'save',
            payload: {
              list: [Object.assign(response.data, responseStatus.data)],
              pagination: {},
            },
          });
        } else {
          yield put({
            type: 'save',
            payload: {
              list: [],
              pagination: {},
            },
          });
          message.error('无效的设备编号');
        }
      } else {
        yield put({
          type: 'save',
          payload: {
            list: [],
            pagination: {},
          },
        });
        message.error('无效的设备编号');
      }
      yield put({ 
        type: 'changeLoading',
        payload: false,
      });
      if (callback) callback(response);
    },
    *revoke({ payload, callback }, { call, put }) {
      yield put({
        type: 'loading',
        payload: true,
      });
      const response = yield call(certificateDelete, payload);
      yield put({ 
        type: 'changeLoading',
        payload: false,
      });
      if (callback) callback(response);
    },


    *clear({ payload, callback }, { call, put }) {
      yield put({
        type: 'save',
        payload: {
          list: [],
          pagination: {},
        },
      });
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    changeLoading(state, action) {
      return {
        ...state,
        loading: action.payload,
      };
    },
  },
};
